package tjuscs.ourmap;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ClipData.Item;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.database.CursorJoiner.Result;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;
import baidumapsdk.demo.R;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.platform.comapi.basestruct.GeoPoint;

public class MainActivity extends Activity {

	final static String TAG = "MainActivty";
	private MapView mMapView = null;

	private MapController mMapController = null;

	FrameLayout mMapViewContainer = null;
	MKMapViewListener mMapListener = null;

	// 登录界面的控件以及用户的id，name，pwd等信息
	private EditText etUser, etPwd;
	private Button btnReg, btnLog;
	private int userId;
	private String userName, userPwd;

	private ArrayList<Integer> groupsId = new ArrayList<Integer>();
	private ArrayList<String> groupsName = new ArrayList<String>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_layout);

		etUser = (EditText) findViewById(R.id.user);
		etPwd = (EditText) findViewById(R.id.pwd);
		btnReg = (Button) findViewById(R.id.reg);
		btnLog = (Button) findViewById(R.id.log);
		btnReg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final JSONObject jsonObject = new JSONObject();
				try {
					jsonObject.put("types", "register");
					jsonObject.put("name", etUser.getText().toString());
					jsonObject.put("passWd", etPwd.getText().toString());
					Log.d(TAG, "jsonObject" + jsonObject);
					
					new Thread(){
						public void run() {
							try {
								JSONObject res = myPost(jsonObject);
								Log.d(TAG, "res = " + res);
								if (res.has("prompt")) {

									if (res.getString("prompt")
											.equals("register successed")) {
										Log.d(TAG, "res" + res);
										userId = res.getInt("userId");
										userName = etUser.getText().toString();
										userPwd = etPwd.getText().toString();
										saveToFile();

										// toMap();
										// ？？？？？？？？？？？？？？？？？？？？连接
										Toast.makeText(getApplicationContext(), "注册成功",
												Toast.LENGTH_SHORT).show();
										startActivity(new Intent(MainActivity.this,
												MainActivity.class));

									}
								} else {
									Toast.makeText(getApplicationContext(), "注册失败",
											Toast.LENGTH_SHORT).show();
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						};
					}.start();
					
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
		});
		btnLog.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				login(Integer.parseInt(etUser.getText().toString()), etPwd
						.getText().toString());
				saveToFile();

				/*
				 * if (etUser.getText().toString().equalsIgnoreCase("123") &&
				 * etPwd.getText().toString().equalsIgnoreCase("123")) {
				 * Toast.makeText(getApplicationContext(), "登录成功",
				 * Toast.LENGTH_SHORT).show(); startActivity(new
				 * Intent(MainActivity.this, DisplayMap.class)); } else {
				 * Toast.makeText(getApplicationContext(), "登录失败",
				 * Toast.LENGTH_SHORT).show(); startActivity(new
				 * Intent(MainActivity.this, MainActivity.class)); }
				 */
			}
		});

		SharedPreferences info = MainActivity.this.getSharedPreferences("user",
				MODE_PRIVATE);
		if (info.getInt("userId", -1) != -1) {
			// 直接使用保存的信息登录
			readFromFile();
			etUser.setText(userId + "");
			etPwd.setText(userPwd);
			login(info.getInt("userId", -1), info.getString("passWd", "none"));
		}

	}

	@Override
	protected void onDestroy() {
		mMapView.destroy();
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	public JSONObject myPost(JSONObject json) {
		try {
			String url = "http://192.168.43.244:8080/funServer/severlet/severlet";
			Log.d(TAG, "213214132");
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
			nameValuePair
					.add(new BasicNameValuePair("param", json.toString()));
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair,
					HTTP.UTF_8));
			Log.d(TAG, "result = ");
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(httpPost);
			Log.d(TAG, "httpResponse = " + httpResponse);

			String result = EntityUtils.toString(httpResponse.getEntity());
			Log.d(TAG, "result = " + result);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				// String result =
				// EntityUtils.toString(httpResponse.getEntity());

				Log.d(TAG, "result = " + result);
				return new JSONObject(result);
			}
		} catch (Exception e) {
			Log.d(TAG,"error"+e.getMessage());
		} finally {
		}
		return new JSONObject();
	}

	public void login(int id, String pwd) {
		JSONObject userInfo = new JSONObject();
		try {
			userInfo.put("types", "login");
			userInfo.put("userId", id);
			userInfo.put("passWd", pwd);
			JSONObject res = myPost(userInfo);
			Log.d(TAG, "logicResponse = " + res.toString());
			if (res.has("isLog") && res.getBoolean("isLog")) {
				userId = id;
				userPwd = pwd;
				// 姓名应该怎么处理？
				userName = res.getString("name");
				int numGroup = res.getInt("groupSize");
				String a="groupsId",b="groupsName";
				groupsId.clear();
				groupsName.clear();
				for(int i = 0;i < numGroup;i++){
					groupsId.add(i, res.getInt(a+i));
					groupsName.add(i,res.getString(b+i));
				}
				// toMap();
				
				Toast.makeText(getApplicationContext(), "登录成功",
						Toast.LENGTH_SHORT).show();

				startActivity(new Intent(MainActivity.this, DisplayMap.class));

			} else {
				Toast.makeText(getApplicationContext(), "登录失败",
						Toast.LENGTH_SHORT).show();
				return;
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		Intent it = new Intent(MainActivity.this, DisplayMap.class);  
		Bundle bundle=new Bundle();
		bundle.putIntegerArrayList("groupsId", groupsId);
		bundle.putStringArrayList("groupsName", groupsName);  
		it.putExtras(bundle); // it.putExtra(“test”, "shuju”);  
		startActivityForResult(it, 0); 
		//startActivity(new Intent(MainActivity.this, DisplayMap.class));
	}

	// 将用户的相关信息保存到文件中
	public void saveToFile() {
		SharedPreferences info = MainActivity.this.getSharedPreferences("user",
				MODE_PRIVATE);
		Editor editor = info.edit();
		editor.putString("userName", userName);
		editor.putInt("userId", userId);
		editor.putString("passWd", userPwd);
		editor.commit();
	}

	// 将文件中存储的用户信息读取到变量中
	public void readFromFile() {
		SharedPreferences info = MainActivity.this.getSharedPreferences("user",
				MODE_PRIVATE);
		userName = info.getString("userName", "none");
		userId = info.getInt("userId", -1);
		userPwd = info.getString("passWd", "none");
	}

	/*
	 * // 发送自己坐标，并接受处理服务器传回的各种数据 public void sendLatLng() { JSONObject latLng =
	 * new JSONObject(); try { latLng.put("userId", ""); latLng.put("lat", "");
	 * latLng.put("lng", ""); JSONObject res = doPost(latLng);
	 * 
	 * if (res.has("GroupAddedNum")) { for (int i = 0; i <
	 * res.getInt("GroupAddedNum"); i++) { // TODO 处理得到的数据
	 * res.getInt("GroupAdded" + i); } }
	 * 
	 * if (res.has("applyInfNum")) { for (int i = 0; i <
	 * res.getInt("applyInfNum"); i++) { // TODO 处理得到的数据 JSONObject applyInfo =
	 * res.getJSONObject("applyInf" + i); applyInfo.getInt("applyId");
	 * applyInfo.getInt("applyGroup"); applyInfo.getString("mes"); } }
	 * 
	 * if (res.has("callInf")) { // TODO 处理得到的数据 JSONObject callInfo =
	 * res.getJSONObject("callInf"); callInfo.getInt("callId");
	 * callInfo.getString("callLat"); callInfo.getString("callLng"); }
	 * 
	 * if (res.has("userNum")) { for (int i = 0; i < res.getInt("userNum"); i++)
	 * { // TODO 处理得到的数据 JSONObject userInfo = res.getJSONObject("userInf" + i);
	 * userInfo.getInt("userInfId"); userInfo.getInt("userInfIsOnline");
	 * userInfo.getString("userInfName"); userInfo.getString("userInfLat");
	 * userInfo.getString("userInfLng"); userInfo.getString("userInfMsg"); } }
	 * 
	 * } catch (JSONException e) { e.printStackTrace(); } }
	 */
}
